/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import app from '@system.app';
import prompt from '@system.prompt';
import dataStorage from '@ohos.data.storage'
import featureAbility from '@ohos.ability.featureAbility'
import config from '../../../share/common/config.js';
import dataParser from '../../../share/common/dataParser';
import {HealthEcologyOperator as hekOperator, BleNotifyType} from '@health-ecology-kit/hek-operator';
import HuaweiAccount from '../../../../js/share/common/scripts/HuaweiAccount';
import TitleBarParams from '../../../share/common/components/titleBar/TitleBarParams';
import SliderBarParams from '../../../share/common/components/sliderBar/SliderBarParams';
import MenuButtonParams from '../../../share/common/components/menuButton/MenuButtonParams';
import DialogBoxParams from '../../../share/common/components/dialog/dialogBox/DialogBoxParams';
import ToggleSwitchParam from '../../../share/common/components/toggleSwitch/ToggleSwitchParams';
import ToggleButtonParams from '../../../share/common/components/toggleButton/ToggleButtonParams';
import AdjusterButtonParams from '../../../share/common/components/adjusterButton/AdjusterButtonParams';
import DeviceStateConstants from '../../../share/common/components/deviceStatusCard/DeviceStateConstants'
import CountdownButtonParams from '../../../share/common/components/countdownButton/CountdownButtonParams';
import ModesSwitchPanelParams from '../../../share/common/components/modesSwitchPanel/ModesSwitchPanelParams';
import InformationPanelParams from '../../../share/common/components/informationPanel/InformationPanelParams';
import DeviceStatusCardTextParams from '../../../share/common/components/deviceStatusCard/plainText/DeviceStatusCardTextParams';
import DeviceStatusCardIconTextParams from '../../../share/common/components/deviceStatusCard/iconText/DeviceStatusCardIconTextParams';
import DeviceStatusCardProgressParams from '../../../share/common/components/deviceStatusCard/progress/DeviceStatusCardProgressParams';
import DeviceStatusCardSingleIconParams from '../../../share/common/components/deviceStatusCard/singleIcon/DeviceStatusCardSingleIconParams';
import DeviceStatusCardDoubleIconParams from '../../../share/common/components/deviceStatusCard/doubleIcon/DeviceStatusCardDoubleIconParams';

const JS_TAG = 'JS/Page/Dashboard/index: ';
const TOKEN_INVALID_ERROR_CODE = 1203;
const NOTIFY_TYPE = BleNotifyType.INDICATION;
const SERVICE_UUID = '0000abcd-0000-0000-0000-000000000000';
const CHARACTER_UUID = '0000abcd-0000-0000-0000-000000000000';

export default {
  data: {
    isFullScreen: false,
    macAddress: undefined,
    //组件数据初始化，必选
    deviceStatus: 0,
    middleTitle: '17:52',
    titlesBarConfig: undefined,
    toggleSwitchData: undefined,
    toggleButtonData: undefined,
    toggleButtonConfig: undefined,
    exceptionHintLabel: undefined,
    adjusterButtonData: undefined,
    countdownButtonData: undefined,
    informationPanelData: undefined,
    modesSwitchPanelData: undefined,
    deviceStatusCardTextData: undefined,
    deviceStatusCardIconTextData: undefined,
    deviceStatusCardProgressData: undefined,
    deviceStatusCardSingleIconData: undefined,
    deviceStatusCardDoubleIconData: undefined,
    deviceStatusType: DeviceStateConstants.TEXT,
  },
  ////////////////////////////////////////
  ////////       生命周期事件      ////////
  onInit() {
    console.debug(JS_TAG + 'onInit.');
    try {
      this.checkAccessToken();
    } catch (e) {
      console.error(JS_TAG + 'checkAccessToken error = ' + e);
    }
    this.initParams();
    this.initComponents();
    this.initBleListeners();
  },
  onShow() {
    console.info(JS_TAG + 'onShow');
  },
  onDestroy() {
    console.info(JS_TAG + 'onDestroy, macAddress = ' + this.macAddress);
    app.terminate();
    this.disconnectToDevice(this.macAddress);
  },
  onHide() {
    console.info(JS_TAG + 'onHide.');
  },
  onBackPress() {
    console.info(JS_TAG + 'onBackPress.');
    this.exit();
  },
  ////////////////////////////////////////
  ///////     页面初始化      ////////
  initParams() {
    this.$app.$def.globalData.isDarkMode = this.isDarkMode;
    console.debug(JS_TAG + 'initParams isDarkMode = ' + this.isDarkMode);
    if (this.params == undefined) {
      console.error(JS_TAG + 'initParams params undefined');
    } else {
      let paramJson = JSON.parse(this.params);
      console.debug(JS_TAG + 'initParams paramJson = ' + JSON.stringify(paramJson));
      this.productId = paramJson.productId;
      this.macAddress = paramJson.macAddress;
      this.$app.$def.globalData.bundleName = this.bundleName;
    }
    this.$app.$def.globalData.productId = this.productId? this.productId: config.customDefaultData.productId;
    this.$app.$def.globalData.macAddress = this.macAddress? this.macAddress: config.customDefaultData.macAddress;
  },
  ////////////////////////////////////////
  ///////      登录状态监测       ////////
  checkAccessToken() {
    HuaweiAccount.refreshAccessToken((data, code) => {
      let date = new Date();
      date.setHours(date.getHours() + 1);
      this.$app.$def.globalData.accessToken = data.access_token;
      this.$app.$def.globalData.accessTokenExpireTimestamp = date.getTime();
    }, this.processCheckAccessTokenFailed)
  },
  processCheckAccessTokenFailed(data, code) {
    console.error(JSON.stringify(data))
    if (data.error == TOKEN_INVALID_ERROR_CODE) {
      this.onLoggedOut();
    }
  },
  async onLoggedOut() {
    let path = await featureAbility.getContext().getFilesDir();
    let storage = dataStorage.getStorageSync(path + '/preferences');
    storage.putSync('rt_expire_timestamp', '0');
    storage.deleteSync('refresh_token');
    storage.flushSync();
    prompt.showDialog({
      message: this.$t('strings.public_logged_out_message'),
      buttons: [
        {
          text: this.$t('strings.public_got_it'),
          color: '#0A59F7',
        },
        {
          text: this.$t('strings.public_log_in'),
          color: '#0A59F7',
        },
      ],
      success: (data) => {
        if (data.index == 1) {
          app.requestFullWindow();
          this.isFullScreen = true;
          this.$app.$def.globalData.isFullScreen = true;
          HuaweiAccount.signIn();
        }
      },
      cancel: () => {
        console.log('dialog cancel callback');
      },
    })
  },
  ////////////////////////////////////////
  ///////     注册蓝牙事件      ///////////
  initBleListeners() {
    console.debug(JS_TAG + 'initBleListeners');
    hekOperator.onBleServiceDiscovered(this.bleServiceDiscoveredCallback);
    hekOperator.onBleConnectionStateChange(this.bleConnectionStateCallback);
    hekOperator.onBluetoothAdapterStateChange(this.bluetoothAdapterStateCallback);
    hekOperator.onBleCharacteristicValueChange(this.bleCharacteristicChangeCallback);
    this.enableNotifyAndIndicate();
  },
  initComponents() {
    this.initTitleBar();
    this.initExceptionHintLabel();
    this.initToggleButton();
    this.initResultCard();
    this.initAdjusterButton();
    this.initToggleSwitch();
    this.initSliderBar();
    this.initMenuButton();
    this.initCountdownButton();
    this.initModesSwitchPanel();
    this.initDialogBox();
    this.initDeviceStatusCardIconText();
    this.initDeviceStatusCardDoubleIcon();
    this.initDeviceStatusCardSingleIcon();
    this.initDeviceStatusCardProgress();
    this.initDeviceStatusCardText();
  },
  ////////////////////////////////////////
  ////////      控件初始化示例     /////////
  initTitleBar() {
    let productId = this.$app.$def.globalData.productId;
    let deviceResource = this.$t('resources.' + productId);
    this.titlesBarConfig = TitleBarParams.getTitleBarConfig(
      {
        title: deviceResource.device_name,
        menuOptions: this.$t('resources.' + productId).menu_options
      });
  },
  initExceptionHintLabel() {
    this.exceptionHintLabel = this.$t('strings.public_battery_low_hint');
  },
  initToggleButton() {
    this.toggleButtonConfig = ToggleButtonParams.getToggleButtonConfig(
      {
        title: 'Toggle Button',
        subTitle: 'on',
        onIcon: '/common/img/base/ic_public_sound_active.png',
        offIcon: '/common/img/base/ic_public_sound_inactive.png'
      });
    this.toggleButtonData = ToggleButtonParams.getToggleButtonData({
      defaultState: true
    });
  },
  initResultCard() {
    this.informationPanelConfig = InformationPanelParams.getInformationPanelConfig({
      config: [
        {
          label: '剩余工作时长',
          unit: ''
        },
        {
          label: '电池电量',
          unit: '%'
        }]
    });
    this.informationPanelData = InformationPanelParams.getInformationPanelData({
      data: [
        {
          value: '14:59'
        },
        {
          value: '10',
          isAbnormal: true
        }]
    });
  },
  initAdjusterButton() {
    this.adjusterButtonConfig = AdjusterButtonParams.getAdjusterButtonConfig({
      title: 'Adjuster Button',
      maxGears: 10,
      minGears: 0,
      step: 1,
    });
    this.adjusterButtonData = AdjusterButtonParams.getAdjusterButtonData({
      defaultValue: 5,
    });
  },
  initToggleSwitch() {
    this.toggleSwitchConfig = ToggleSwitchParam.getToggleSwitchConfig(
      {
        title: 'Toggle Switch',
        subTitle: 'SubTitle',
        initialState: false
      }
    );
    this.toggleSwitchData = ToggleSwitchParam.getToggleSwitchData({
      defaultState: false,
    });
  },
  initSliderBar() {
    this.sliderBarConfig = SliderBarParams.getSliderBarConfig({
      title: 'Slider Bar',
      unit: '%'
    });
  },
  initMenuButton() {
    this.menuButtonConfig = MenuButtonParams.getMenuButtonConfig({
      title: 'Menu Button',
      activeIcon: '/common/img/base/ic_public_sound_active.png',
      inactiveIcon: '/common/img/base/ic_public_sound_inactive.png',
      selectOptions: [
        {
          index: 0,
          describe: 'strings.option1',
          value: 1,
        },
        {
          index: 1,
          describe: 'strings.option2',
          value: 2,
        },
        {
          index: 2,
          describe: 'strings.option3',
          value: 3,
        },
      ],
    });
  },
  initCountdownButton() {
    this.countdownButtonConfig = CountdownButtonParams.getCountdownButtonConfig({
      title: 'Countdown Button',
      indicatorSuffix: 'minutes',
      range: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    });
    this.countdownButtonData = CountdownButtonParams.getCountdownButtonData({
      defaultValue: 5,
      defaultSubTitle: 5 + ' minutes'
    });
  },
  initModesSwitchPanel() {
    this.modesSwitchPanelConfig = ModesSwitchPanelParams.getModesSwitchPanelConfig({
      defaultMode: undefined,
      items: [
        {
          mode: 1,
          title: 'Mode 1',
          activeIcon: '/common/img/base/ic_public_sound_active.png',
          inactiveIcon: '/common/img/base/ic_public_sound_inactive.png'
        },
        {
          mode: 2,
          title: 'Mode 2',
          activeIcon: '/common/img/base/ic_public_sound_active.png',
          inactiveIcon: '/common/img/base/ic_public_sound_inactive.png'
        },
        {
          mode: 3,
          title: 'Mode 3',
          activeIcon: '/common/img/base/ic_public_sound_active.png',
          inactiveIcon: '/common/img/base/ic_public_sound_inactive.png'
        },
      ]
    });
    this.modesSwitchPanelData = ModesSwitchPanelParams.getModesSwitchPanelData({
      defaultMode: 2
    });
  },
  initDialogBox() {
    this.infoConfig = DialogBoxParams.getInfoConfig({
      info: 'Dialog info'
    });
    this.textPickerConfig = DialogBoxParams.getTextPickerConfig({
      titleConfig: {
        title: 'Text Picker Dialog',
        subTitle: 'Subtitle',
      },
      items: ['1', '2', '3'],
      indicatorSuffix: '后',
      indicatorPrefix: '前',
    });
    this.textPickerData = DialogBoxParams.getTextPickerData({
      defaultIndex: 0
    });
    this.listSelectorConfig = DialogBoxParams.getListSelectorConfig({
      titleConfig: {
        title: 'List Selector Dialog',
        subTitle: 'Subtitle'
      },
      mode: 1,
      items: [
        {
          title: 'Item 1 title',
          subTitle: 'Item 1 subtitle',
        },
        {
          title: 'Item 2 title',
        },
        {
          title: 'Item 3 title',
          subTitle: 'Item 3 subtitle',
        },
        {
          title: 'Item 4 title',
        },
      ],
      inactiveIcon: 'common/img/base/ic_public_sound_inactive.png',
      activeIcon: 'common/img/base/ic_public_sound_active.png',
      itemCanClick: true,
    });
    this.listSelectorData = DialogBoxParams.getListSelectorData({
      defaultIndex: [0, 2],
    });
  },
  initDeviceStatusCardDoubleIcon() {
    this.deviceStatusCardDoubleIconData = DeviceStatusCardDoubleIconParams.getDeviceStatusCardDoubleIconData({
      middleTitle: this.middleTitle,
      title: '工作中',
      subTitle: '剩余工作时长',
      firstIcon: '/common/img/base/ic_public_close.png',
      secondIcon: '/common/img/base/ic_public_pause.png',
    });
  },
  initDeviceStatusCardSingleIcon() {
    this.deviceStatusCardSingleIconData = DeviceStatusCardSingleIconParams.getDeviceStatusCardSingleIconData({
      title: '已开启',
      middleTitle: '',
      subTitle: '',
      iconPath: '/common/img/base/ic_public_off.png',
    });
  },
  initDeviceStatusCardProgress() {
    this.deviceStatusCardProgressData = DeviceStatusCardProgressParams.getDeviceStatusCardProgressData({
      title: '连接中',
    });
  },
  initDeviceStatusCardText() {
    this.deviceStatusCardTextData = DeviceStatusCardTextParams.getDeviceStatusCardTextData({
      title: '未连接',
      middleTitle: '',
      subTitle: '',
      rightText: '重新连接',
    });
  },
  initDeviceStatusCardIconText() {
    this.deviceStatusCardIconTextData = DeviceStatusCardIconTextParams.getDeviceStatusCardIconTextData({
      title: '运行中',
      middleTitle: '',
      subTitle: '',
      rightText: '60',
      rightTextUnit: '%',
      iconPath: '/common/img/base/ic_public_battery.png',
    })
  },
  ////////////////////////////////////////
  ////////     控件事件处理示例    /////////
  onAlertClicked(){
    this.showUndevelopedWarning('onAlertClicked(changeEvent).');
  },
  onToggleButtonClicked() {
    this.showUndevelopedWarning('onToggleButtonClicked(changeEvent).');
  },
  onAdjustNotify(changeEvent) {
    this.showUndevelopedWarning('onAdjustNotify(changeEvent).');
    this.adjustValue = changeEvent.detail.value;
    console.debug(JS_TAG + 'onAdjustNotify adjustValue = ' + this.adjustValue);
  },
  onToggleSwitchClicked(changeEvent) {
    this.showUndevelopedWarning('onToggleSwitchClick(changeEvent).');
    console.debug(JS_TAG + 'onToggleSwitchClick ToggleSwitchState = ' + changeEvent.detail.value);
  },
  onSliderValueChange(changeEvent) {
    this.showUndevelopedWarning('onMenuButtonSelected(changeEvent).');
    console.debug(JS_TAG + 'onSliderValueChange changeValue = ' + changeEvent.detail.value);
  },
  onMenuButtonSelected(changeEvent) {
    this.showUndevelopedWarning('onMenuButtonSelected(changeEvent).');
    console.debug(JS_TAG + 'onSelected changeValue = ' + changeEvent.detail.value);
    this.selectButtonState = changeEvent.detail.value > 0;
  },
  onCountDownStateChange(changeEvent) {
    this.showUndevelopedWarning('onCountDownStateChange(changeEvent).');
    console.debug(JS_TAG + 'onCountDownStateChange changeValue = ' + changeEvent.detail.value);
    this.countdownButtonData = CountdownButtonParams.getCountdownButtonData({
      defaultValue: changeEvent.detail.value,
      defaultSubTitle: changeEvent.detail.value + ' minutes'
    })
  },
  onModeChange(changeEvent) {
    this.showUndevelopedWarning('onModeChange(changeEvent).');
    console.debug(JS_TAG + 'onModeChange changeValue = ' + changeEvent.detail.value.mode + ' , ' + JSON.stringify(changeEvent));
  },
  showTextPickerDialog() {
    this.$element('textPickerDialog').show();
  },
  showListSelectorDialog() {
    this.$element('listSelectorDialog').show();
  },
  showInfoDialog() {
    this.$element('infoDialog').show();
  },
  onClickItem(changeEvent) {
    console.debug(JS_TAG + 'onClickItem changeEvent = ' + JSON.stringify(changeEvent));
  },
  onTextPickerConfirmed(changeEvent) {
    this.showUndevelopedWarning('onTextPickerConfirmed(changeEvent).');
    console.debug(JS_TAG + 'onTextPickerConfirmed changeEvent = ' + JSON.stringify(changeEvent));
    this.$element('textPickerDialog').close();
  },
  onListSelectorConfirmed(changeEvent) {
    this.showUndevelopedWarning('onListSelectorConfirmed(changeEvent).');
    console.debug(JS_TAG + 'onListSelectorConfirmed changeEvent = ' + JSON.stringify(changeEvent));
    this.$element('listSelectorDialog').close();
  },
  closeTextPickerDialog(changeEvent) {
    console.debug(JS_TAG + 'onCloseDialog changeEvent = ' + JSON.stringify(changeEvent));
  },
  closeListSelectorDialog(changeEvent) {
    console.debug(JS_TAG + 'onCloseDialog changeEvent = ' + JSON.stringify(changeEvent));
  },
  closeInfoDialog(changeEvent) {
    this.showUndevelopedWarning('closeInfoDialog(changeEvent).');
    console.debug(JS_TAG + 'onCloseDialog changeEvent = ' + JSON.stringify(changeEvent));
    this.$element('infoDialog').close();
  },
  onClickRight(changeEvent) {
    console.debug(JS_TAG + 'onClickRight changeEvent = ' + JSON.stringify(changeEvent));
  },
  onClickText() {
    this.deviceStatus = 1;
    this.updateDeviceStatusType(DeviceStateConstants.SINGLE_ICON);
  },
  onClickIcon() {
    this.deviceStatus = 2;
    this.updateDeviceStatusType(DeviceStateConstants.DOUBLE_ICON);
  },
  onClickLeftIcon() {
    this.deviceStatus = 4;
    this.updateDeviceStatusType(DeviceStateConstants.PROGRESS);
  },
  onClickRightIcon() {
    console.debug('onClickRightIcon: ' + this.deviceStatus);
    if (this.deviceStatus == 2) {
      this.deviceStatus = 3;
      this.deviceStatusCardDoubleIconData = DeviceStatusCardDoubleIconParams.getDeviceStatusCardDoubleIconData({
        middleTitle: this.middleTitle,
        title: '已暂停',
        subTitle: '剩余工作时长',
        firstIcon: '/common/img/base/ic_public_close.png',
        secondIcon: '/common/img/base/ic_public_start.png',
      });
    } else {
      this.deviceStatus = 2;
      this.deviceStatusCardDoubleIconData = DeviceStatusCardDoubleIconParams.getDeviceStatusCardDoubleIconData({
        middleTitle: this.middleTitle,
        title: '工作中',
        subTitle: '剩余工作时长',
        firstIcon: '/common/img/base/ic_public_close.png',
        secondIcon: '/common/img/base/ic_public_pause.png',
      });
    }
  },
  updateDeviceStatusType(newDeviceStatusType) {
    // 使用此函数以在状态之间进行转换，对应状态将显示对应的页面。
    console.debug('Trying changing deviceStatusCardType to: ' + newDeviceStatusType);
    this.deviceStatusType = newDeviceStatusType;
  },
  requestFullWindow() {
    this.$app.$def.globalData.isFullScreen = true;
    this.isFullScreen = true;
    app.requestFullWindow();
  },
  exit() {
    console.info(JS_TAG + 'exit.');
    app.terminate();
  },
  showUndevelopedWarning(promptMessage) {
    prompt.showToast({
      message: 'Please implement: ' + promptMessage,
      duration: 1000
    });
  },
  ////////////////////////////////////////
  ////////       蓝牙接口调用       ////////
  reConnect() {
    console.debug(JS_TAG + 'Reconnect!')
    hekOperator.getBluetoothAdapterState({
      success: this.onCheckAdapterStateSuccess,
      fail: this.onCheckAdapterStateFailed
    });
  },
  connectToDevice(deviceId) {
    hekOperator.createBleConnection({
      deviceId: deviceId,
      isAutoConnect: false,
      success: () => {
        console.debug(JS_TAG + 'Create ble connection success!');
      },
      fail: this.onDeviceConnectFailed
    })
  },
  disconnectToDevice(deviceId) {
    hekOperator.closeBleConnection({
      deviceId: deviceId,
      success: () => {
        console.debug(JS_TAG + 'Close ble connection success!');
      },
      fail: (code, err) => {
        console.error(JS_TAG + 'Close ble connection error, code is ' + code + ', message is ' + JSON.stringify(err));
      }
    })
  },
  async enableNotifyAndIndicate() {
    hekOperator.notifyBleCharacteristicValueChange({
      deviceId: this.macAddress,
      serviceId: SERVICE_UUID,
      characteristicId: CHARACTER_UUID,
      notifyType: NOTIFY_TYPE,
      success: () => {
        console.debug(JS_TAG + 'Enable notify and indicate success!');
      },
      fail: this.onEnableNotifyFailed
    });
  },
  ////////////////////////////////////////
  ////////        蓝牙回调处理       ///////
  bluetoothAdapterStateCallback(adapterState) {
      adapterState.isAvailable ? this.onAdapterAvailable() : this.onAdapterNotAvailable();
  },
  bleConnectionStateCallback(connectionState) {
    console.debug(JS_TAG + 'Connection state changed: ' + JSON.stringify(connectionState));
    if (connectionState.deviceId != this.macAddress) {
      return;
    }
    if (connectionState.isConnected) {
      this.exceptionHintLabel = 'Device connected.';
    } else {
      this.exceptionHintLabel = 'Device disconnected.';
    }
  },
  bleServiceDiscoveredCallback(bleServiceDiscoveredResult) {
    console.debug(JS_TAG + 'onBleServiceDiscovered = ' + JSON.stringify(bleServiceDiscoveredResult));
    if (bleServiceDiscoveredResult.isDiscoverySuccess) {
      this.enableNotifyAndIndicate();
    } else {
      console.error(JS_TAG + 'ble service discovered failed.');
    }
  },
  bleCharacteristicChangeCallback(bleCharacteristicChangeValue) {
    if (bleCharacteristicChangeValue.deviceId != this.macAddress) {
      return;
    }
    this.showUndevelopedWarning('bleCharacteristicChangeCallback().');
    console.debug(JS_TAG + 'onBleCharacteristicValueChange result = ' + JSON.stringify(bleCharacteristicChangeValue));
    // 处理设备上报的特征值，需要开发者自行实现具体的协议解析
    let result = dataParser.dealWithCharacteristicValue(bleCharacteristicChangeValue.deviceId,
      bleCharacteristicChangeValue.characteristicId, bleCharacteristicChangeValue.characteristicData);
  },
  ////////////////////////////////////////
  ////////        页面流程处理       ///////
  onDeviceConnectFailed(errorCode, errorMessage) {
    this.showUndevelopedWarning('onDeviceConnectFailed().');
  },
  onDeviceDiscoveryFailed(errorCode, errorMessage) {
    this.showUndevelopedWarning('onDeviceDiscoveryFailed().');
  },
  onServiceDiscoveredFailed() {
    this.showUndevelopedWarning('onServiceDiscoveredFailed().');
  },
  onEnableNotifyFailed(errorCode, errorMessage) {
    this.showUndevelopedWarning('onEnableNotifyFailed().');
  },
  onAdapterOpenFailed(errorCode, errorMessage) {
    this.showUndevelopedWarning('onAdapterOpenFailed().');
  },
  onStopDeviceDiscoveryFailed(errorCode, errorMessage) {
    this.showUndevelopedWarning('onStopDeviceDiscoveryFailed().');
  },
  onCheckAdapterStateSuccess(bluetoothAdapterState) {
    console.debug(JS_TAG + 'Bluetooth adapter state is:' + JSON.stringify(bluetoothAdapterState));
    bluetoothAdapterState.isAvailable ? this.onAdapterAvailable() : this.onCheckAdapterNotAvailable();
  },
  onCheckAdapterStateFailed(errorCode, errorMessage) {
    this.showUndevelopedWarning('onCheckAdapterStateFailed().');
  },
  onStartDiscoverySuccess() {
    this.showUndevelopedWarning('onStartDiscoverySuccess().');
  },
  onTargetDeviceFound(deviceId) {
    this.showUndevelopedWarning('onTargetDeviceFound().');
  },
  onStartConnectSuccess() {
    this.showUndevelopedWarning('onStartConnectSuccess().');
  },
  onServiceDiscoveredSuccess() {
    this.showUndevelopedWarning('onServiceDiscoveredSuccess().');
  },
  onCheckAdapterNotAvailable() {
    this.showUndevelopedWarning('onCheckAdapterNotAvailable().');
    console.error(JS_TAG + 'Bluetooth adapter state not available.');
  },
  onAdapterAvailable() {
    this.showUndevelopedWarning('onAdapterAvailable().');
    if (config.scanRequired) {
      // 若需要扫描，请开发者自行添加相关代码，参考connection/pages/index.js
    } else {
      this.connectToDevice(this.macAddress);
    }
  },
  onAdapterNotAvailable() {
    this.showUndevelopedWarning('onAdapterNotAvailable().');
  }
}
